package com.interview.service.impl;

import com.interview.dao.ArticleMapper;
import com.interview.dao.CatalogueMapper;
import com.interview.dao.ParameterMapper;
import com.interview.pojo.Article;
import com.interview.pojo.Catalogue;
import com.interview.pojo.Parameter;
import com.interview.pojo.Solr_Article;
import com.interview.service.ArticleService;
import com.interview.service.utils.Springboot_SolrUtils;
import com.interview.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service("ArticleServiceImpl")
public class ArticleServiceImpl implements ArticleService {


    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ParameterMapper parameterMapper;

    @Autowired
    private CatalogueMapper catalogueMapper;


    @Autowired
    private Springboot_SolrUtils solrUtils;

    //添加文章内容数据

    @Override
    public void add(Article article) {
        try {


            Article article2=new Article();
            article2.setHead(article.getHead());
            int i1 = articleMapper.selectCount(article2);
            if (i1>=1){
                System.out.println("已存在此篇文章");
                return;
            }


            int i = articleMapper.count(article.getCatalogue_id());


            articleMapper.insertSelective(article);

            //目录数量+1
            Catalogue catalogue=new Catalogue();
            catalogue.setId(article.getCatalogue_id());
            catalogue.setCatalogue_size(i+1);
            catalogueMapper.updateByPrimaryKeySelective(catalogue);

            RedisUtis.setStringRedis("interview-queryID-Article"+article.getId(),article);
            //缓存
            //---删除缓存 和更新缓存  全部文章的缓存
            RedisUtis.delKeyRedis("interview-queryAll-Article");
            queryAll(); //更新缓存

            RedisUtis.delKeyRedis("interview-query-Article"+article.getCatalogue_id());
            Article article1=new Article();
            article1.setCatalogue_id(article.getCatalogue_id());
            query(article1);




            //添加到搜索里
            Solr_Article solr_article=new Solr_Article();
            solr_article.setId(article.getId());
            solr_article.setHead(article.getHead());
            solr_article.setTime(article.getTime());
            solr_article.setType(article.getCatalogue_id());
            solr_article.setUrl_params("catalogueId="+article.getId());
            solrUtils.soleAdd(solr_article);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void del(Article article) {
        try {
            Article article1 = queryID(article);
            int i = articleMapper.count(article1.getCatalogue_id());
            articleMapper.delete(article);

            //目录数量-1
            Catalogue catalogue=new Catalogue();
            catalogue.setId(article1.getCatalogue_id());
            catalogue.setCatalogue_size(i-1);
            catalogueMapper.updateByPrimaryKeySelective(catalogue);

            //删除指定文章
            RedisUtis.delKeyRedis("interview-queryID-Article"+article.getId());
            //缓存
            //---删除缓存 和更新缓存  全部文章的缓存


            RedisUtis.delKeyRedis("interview-query-Article"+article1.getCatalogue_id());
            Article article2=new Article();
            article2.setCatalogue_id(article.getCatalogue_id());
            query(article2);


            RedisUtis.delKeyRedis("interview-queryAll-Article");
            queryAll(); //更新缓存
            //删除指定搜索
            solrUtils.deleteDocument(article.getId());


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void up(Article article) {
        //删除指定文章
        RedisUtis.delKeyRedis("interview-queryID-Article"+article.getId());

        //缓存
        //---删除缓存 和更新缓存  全部文章的缓存
        RedisUtis.delKeyRedis("interview-query-Article"+article.getCatalogue_id());
        Article article2=new Article();
        article2.setCatalogue_id(article.getCatalogue_id());
        query(article2);


        RedisUtis.delKeyRedis("interview-queryAll-Article");
        queryAll(); //更新缓存

        articleMapper.updateByPrimaryKeySelective(article);

        //更新标签下的文章数量
        int i = articleMapper.count(article.getCatalogue_id());
        Catalogue catalogue=new Catalogue();
        catalogue.setId(article.getCatalogue_id());
        catalogue.setCatalogue_size(i);
        catalogueMapper.updateByPrimaryKeySelective(catalogue);

    }


    // 查询每日 推荐 4篇文章

    @Override
    public List<Article> queryRecommend() {
        //1. 判断当前时间是否大于数据库里记录的时间 1天  如果大于了 那么就更新缓存里的数据
        Parameter parameter=new Parameter();
        parameter.setParameter_key("recommend_article_time");
        Parameter parameter1 = parameterMapper.selectOne(parameter);
        // 左边小 0  左边大 1
        long dateStrPoor = getDateStrPoor( DateUtils.dateStrng(),parameter1.getParameter_value());
        if (dateStrPoor>=1) {//满足条件


            //查询数据库数据
            List<Article> articles = articleMapper.queryRecommend();

            RedisUtis.setStringRedis("interview-"+parameter.getParameter_key(),articles );
            //更新数据库的时间为当前时间
            parameter.setId("730-2021lI1nX7pT14cH26gX3o198K-314");
            parameter.setParameter_value(DateUtils.dateStrng());
            parameterMapper.updateByPrimaryKeySelective(parameter);
            return articles;

        }
        //2.查询redis缓存内容数据
        String stringRedis = RedisUtis.getStringRedis("interview-"+parameter.getParameter_key());

        if (!NullUtils.notEmpty(stringRedis)) {
            //查询数据库数据
            List<Article> articles = articleMapper.queryRecommend();


            RedisUtis.setStringRedis("interview-"+parameter.getParameter_key(),articles );
            return articles;
        }

        List<Article> objects = JsonTurnUtils.jsonTurnList(stringRedis, Article.class);

        return objects;
    }



    // 查询 随机 10 篇文章

    @Override
    public List<Article> queryRandom() {

        //查询缓存
        String stringRedis = RedisUtis.getStringRedis("interview-queryAll-Article");

        //如果缓存不存在那么就查询数据库
        if (!NullUtils.notEmpty(stringRedis)) {
            List<Article> articles = articleMapper.queryRandom();
            Collections.shuffle(articles); //进行顺序打乱
            List<Article> list=new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                list.add(articles.get(i))  ;
            }


            return  list;
        }
        //缓存存在 查询缓存
        List<Article>  objects = JsonTurnUtils.jsonTurnList(stringRedis, Article.class);
        Collections.shuffle(objects); //进行顺序打乱
        List<Article> list=new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(objects.get(i))  ;
        }

        return list;
    }



// 查询全部 文章
    @Override
    public List<Article> queryAll() {
        String stringRedis = RedisUtis.getStringRedis("interview-queryAll-Article");
        //如果文章不存在 查询数据库 并存入缓存中
        if (!NullUtils.notEmpty(stringRedis)) {
            List<Article> titles = articleMapper.queryAll();
            RedisUtis.setStringRedis("interview-queryAll-Article",titles);
            return titles;
        }
        //缓存数据
        List<Article>  objects = JsonTurnUtils.jsonTurnList(stringRedis,Article.class);
        return  objects;
    }

    @Override
    public int query_Count() {
        return articleMapper.query_Count();
    }


    public Example createExampleSelect(Article article) {
        Example example = new Example(Article.class);
        Example.Criteria criteria = example.createCriteria();
        if(article!=null){
            // 如果name不为空 模糊匹配查询name字段
            if(!StringUtils.isEmpty(article.getCatalogue_id())){
                criteria.andEqualTo("catalogue_id",article.getCatalogue_id());
            }
            //去重复
            example.setDistinct(true);
            example.orderBy("time").desc();
        }

        return example;
    }

    @Override
    public List<Article> query(Article article) {

        String stringRedis = RedisUtis.getStringRedis("interview-query-Article"+article.getCatalogue_id());
        if (!NullUtils.notEmpty(stringRedis)) {
            List<Article> catalogues = articleMapper.selectByExample(createExampleSelect(article));

            RedisUtis.setStringRedis("interview-query-Article"+article.getCatalogue_id(), catalogues);

            return  catalogues;
        }
        List<Article> objects = JsonTurnUtils.jsonTurnList(stringRedis, Article.class);
        return objects ;
    }

    //查询指定文章
    @Override
    public Article queryID(Article article) {

        String stringRedis = RedisUtis.getStringRedis("interview-queryID-Article"+ article.getId());
        if (!NullUtils.notEmpty(stringRedis)) {
            Article article1 = articleMapper.selectOne(article);
            RedisUtis.setStringRedis("interview-queryID-Article"+ article.getId(), article1);

            return  article1 ;

        }

        Article  objects = JsonTurnUtils.jsonTurnJavaBena(stringRedis, Article.class);

        return objects ;
    }

    @Override
    public List<Article> queryName(Article article) {
        return articleMapper.selectByExample(createExampleSelect_Name(article));
    }

    @Override
    public int time_count(String time1, String time2) {
        return articleMapper.time_count(time1,time2);
    }

    public Example createExampleSelect_Name(Article article) {
        Example example = new Example(Article.class);
        Example.Criteria criteria = example.createCriteria();
        if(article!=null){
            // 如果name不为空 模糊匹配查询name字段
            if(!StringUtils.isEmpty(article.getHead())){
                criteria.andLike("head","%"+article.getHead()+"%");
            }
            //去重复
            example.setDistinct(true);
        }

        return example;
    }

    //   endDate 减  nowDate
    public static long getDateStrPoor(String endDate, String nowDate) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = null;
        Date date2 = null;
        try {
            date1 = format.parse(endDate);
            date2 = format.parse(nowDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = date1.getTime() - date2.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day;
    }
}
